from django import forms
from core.models.class_task_todo import ClassTaskTodo
from django.utils import timezone
from django.contrib.auth.models import User


class ClassTaskTodoForm(forms.ModelForm):
    TASK_TYPE_CHOICES = [
        ('homework', '作业任务'),
        ('discipline', '纪律检查'),
        ('leave', '请假申请')
    ]
    
    task_type = forms.ChoiceField(
        choices=TASK_TYPE_CHOICES,
        label='任务类型',
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    
    description = forms.CharField(
        label='任务描述',
        widget=forms.Textarea(attrs={'rows': 3, 'class': 'form-control'})
    )
    
    status = forms.ChoiceField(
        label='任务状态',
        choices=[],
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    
    assigned_to = forms.ModelChoiceField(
        queryset=User.objects.filter(groups__name='teachers'),
        label='负责人',
        widget=forms.Select(attrs={'class': 'form-control'})
    )

    resolution = forms.CharField(
        label='解决方案',
        required=False,
        widget=forms.Textarea(attrs={'rows': 3, 'class': 'form-control'})
    )

    start_time = forms.DateTimeField(
        label='开始时间',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control date-picker',
                'placeholder': '选择开始日期时间'
            })
    )
    end_time = forms.DateTimeField(
        label='截止时间',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control date-picker',
                'placeholder': '选择截止日期时间'
            })
    )
    completed_at = forms.DateTimeField(
        label='完成时间',
        required=False,
        widget=forms.DateTimeInput(
            attrs={
                'type': 'datetime-local',
                'class': 'form-control',
                'min': timezone.now().strftime('%Y-%m-%dT%H:%M')
            }
        )
    )

    class Meta:
        model = ClassTaskTodo
        fields = ['task_type', 'description', 'status', 'assigned_to', 'resolution', 'start_time', 'end_time', 'completed_at']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['status'].choices = self.get_available_status_choices()

    def get_available_status_choices(self):
        current_status = self.instance.status
        allowed = {
            'pending': [('processing', '处理中'), ('cancelled', '已取消')],
            'processing': [('completed', '已完成'), ('pending', '待处理')],
            'completed': [],
            'cancelled': []
        }
        return allowed.get(current_status, [])

    def clean_status(self):
        new_status = self.cleaned_data['status']
        if not self.instance.can_change_status(new_status, self.user):
            raise forms.ValidationError('非法状态变更')
        return new_status

    def clean_assigned_to(self):
        assigned = self.cleaned_data['assigned_to']
        if assigned and not assigned.has_perm('core.change_classtasktodo'):
            raise forms.ValidationError('指定负责人没有处理权限')
        return assigned